import { query2 } from "../../mysqlQuery.js";
import Joi from "joi";
import { getRandomId } from "../../common/index.js";
import SDTime from "silly-datetime"; //时间格式化处理插件
//新增字典
function addDict(req, res, next) {
  const schema = Joi.object().keys({
    type: Joi.string().required(),
    name: Joi.string().required(),
    value: Joi.string().required(),
    keyValue: Joi.number().required(),
  });
  const result = Joi.validate(req.body, schema, { allowUnknown: true });
  if (result.error != null) {
    next(result.error);
    return;
  }
  query2([
    {
      sql: "insert into dictlist (dict_id,type,name,create_time,value,keyValue) values (?,?,?,?,?,?)",
      values: [
        getRandomId(8),
        req.body.type,
        req.body.name,
        SDTime.format(new Date(), "YYYY-MM-DD HH:mm:ss"),
        req.body.value,
        req.body.keyValue,
      ],
    },
  ])
    .then((out) => {
      res.send({
        code: 200,
        msg: "新增成功!",
        data: out[0].rows,
      });
    })
    .catch((err) => {
      next(err);
    });
}
//删除字典
function loseDict(req, res, next) {
  const schema = Joi.object().keys({
    dict_ids: Joi.string().required(), //例：12,33,444
  });
  const result = Joi.validate(req.body, schema, { allowUnknown: true });
  if (result.error != null) {
    next(result.error);
    return;
  }
  let sql = "",
    values = [];
  if (req.body.dict_ids) {
    let dictArr = req.body.dict_ids.split(",");
    dictArr.forEach((element) => {
      sql += "delete from dictlist where dict_id=?;";
      values.push(element);
    });
  }
  query2([
    {
      sql,
      values,
    },
  ])
    .then((out) => {
      res.send({
        code: 200,
        msg: "删除成功!",
        data: out[0].rows,
      });
    })
    .catch((err) => {
      next(err);
    });
}
//修改字典
function putDict(req, res, next) {
  const schema = Joi.object().keys({
    name: Joi.string().required(),
    value: Joi.string().required(),
    keyValue: Joi.number().required(),
    dict_id: Joi.number().required(),
  });
  const result = Joi.validate(req.body, schema, { allowUnknown: true });
  if (result.error != null) {
    next(result.error);
    return;
  }
  query2([
    {
      sql: "update dictlist set name=?,value=?,keyValue=? where dict_id=?",
      values: [
        req.body.name,
        req.body.value,
        req.body.keyValue,
        req.body.dict_id,
      ],
    },
  ])
    .then((out) => {
      res.send({
        code: 200,
        msg: "修改成功!",
        data: out[0].rows,
      });
    })
    .catch((err) => {
      next(err);
    });
}
//查询字典
function getDict(req, res, next) {
  query2([
    {
      sql: "select * from dictlist",
      values: [],
    },
  ])
    .then((out) => {
      let map = new Map();
      let realArr = [];
      out[0].rows.forEach((item) => {
        if (!map.has(item.type)) {
          map.set(item.type, true);
          realArr.push({
            name: item.name,
            type: item.type,
            list: [
              {
                [item.keyValue]: item.value,
              },
            ],
          });
        } else {
          let cun = realArr.filter((child) => child.type == item.type);
          cun[0].list.push({
            [item.keyValue]: item.value,
          });
        }
      });
      res.send({
        code: 200,
        msg: "查询成功！",
        data: realArr,
      });
    })
    .catch((err) => {
      next(err);
    });
}
export { addDict, loseDict, putDict, getDict };
